package com.mx.base.language.script

import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.File

/**
 * @author: xiao.ma
 * Date: 2022/1/25 19:18
 * Desc:该脚本只适合处理通过ExportScript 且byLanguageCategory=true 导出的excel
 */
object ImportScript2 {

    /**
     * 从Excel读取国家化语言包 ,该函数只适合读通过 ExportScript到出的excel
     * @param baseLanguage
     * @param excelLanguageFile excel文件
     * @return
     */
    private fun readLanguageFromExcel(
        baseLanguage: String,
        excelLanguageFile: File,
    ): MutableMap<String, String> {
        if (!excelLanguageFile.exists())
            return mutableMapOf()
        val languageMap = mutableMapOf<String, String>()
        val workbook = WorkbookFactory.create(excelLanguageFile)
        val sheet = workbook.getSheet("sheet")
        val header = sheet.getRow(0)
        if (header != null
            && header.getCell(0).stringCellValue == baseLanguage
            && header.getCell(1).stringCellValue == excelLanguageFile.name.substringBefore(".")
        ) {
            val firstRowIndex = sheet.firstRowNum + 2 //前两行是values- 和对应语言翻译所以不读
            val lastRowIndex = sheet.lastRowNum
            for (rowIndex in firstRowIndex..lastRowIndex) {
                val row = sheet.getRow(rowIndex)
                if (row != null) {
                    val key = row.getCell(0)?.stringCellValue
                    if (!key.isNullOrBlank()) {
                        val languageValue = row.getCell(1)?.stringCellValue
                        if (!languageValue.isNullOrEmpty()) {
                            languageMap[key] = languageValue
                        }
                    }
                }

            }
        }
        workbook.close()
        return languageMap
    }

    fun getTranslateExcelFiles(excelDir: String): Array<File> {
        return File(excelDir).listFiles { file -> file.name.startsWith("values") } ?: arrayOf()
    }

    fun genStringsXml(
        moduleFile: File,
        resPath: String,
        baseLanguage: String,
        excelDir: String,
        targets: List<String>,
        update: Boolean = false,
        fill: Boolean = false
    ) {
        val baseXmlMap =
            XmlHelper.readStringXml("${moduleFile.absolutePath}/$resPath/$baseLanguage/strings.xml")
        if (baseXmlMap.isEmpty()) {
            println("没有需要翻译的文本")
            return
        }
        targets.forEach { target ->
            println("=====f>$target")
            val excelFile = File("$excelDir\\${moduleFile.name}\\$target.xlsx")
            if (excelFile.exists()) {
                XmlHelper.genTargetStringsXml(
                        "${moduleFile.absoluteFile}/$resPath/$target/strings.xml",
                        baseXmlMap,
                        readLanguageFromExcel(baseLanguage, excelFile),
                        update,
                        fill
                )
            } else {
                println("not found,$moduleFile.absoluteFile")
            }
        }

    }

    class Builder {
        private var projectPath = ""
        private var resPath = "src/main/res"
        private var baseLanguage = "values-zh-rCN"
        private var targets = mutableListOf<String>()
        private var excelDir = ""

        private var update = false

        private var fill = false

        fun setProjectPath(projectPath: String): Builder {
            this.projectPath = projectPath
            return this
        }

        fun setBaseLanguage(baseLanguage: String): Builder {
            this.baseLanguage = baseLanguage
            return this
        }

        fun setTargets(targets: MutableList<String>): Builder {
            this.targets = targets
            return this
        }

        fun setExcelDir(excelFilePath: String): Builder {
            this.excelDir = excelFilePath
            return this
        }

        fun setUpdate(update: Boolean): Builder {
            this.update = update
            return this
        }

        fun setFill(fill: Boolean): Builder {
            this.fill = fill
            return this
        }

        private fun fileFilter(file: File): Boolean {
            return file.isDirectory
                    && !file.name.startsWith(".")
                    && File(
                    file.absolutePath,
                    "$resPath/$baseLanguage/strings.xml"
            ).run {
                exists() && isFile
            }
        }

        fun build() {

            File(projectPath)
                .listFiles { file -> fileFilter(file) }?.forEach { module ->
                    if (targets.isEmpty()) {
                        targets = getTranslateExcelFiles("$excelDir\\${module.name}")
                            .map { file -> file.name.substringBefore(".") }
                            .toMutableList()
                    }
                    genStringsXml(
                            moduleFile = module,
                            resPath = resPath,
                            baseLanguage = baseLanguage,
                            excelDir = excelDir,
                            targets = targets,
                            update = update,
                            fill = fill
                    )
                }

        }
    }
}

fun main() {

    ImportScript2.Builder()
        .setExcelDir("D:\\Language")
        .setProjectPath("C:\\Android\\wk\\peanut_gbg_peanut_v9.12.10.1x")
        .setBaseLanguage("values-zh-rCN")
        .setTargets(mutableListOf("values-ro-rRO"))
        .setUpdate(true)
        .setFill(true)
        .build()

}
